package pl.asoft.nbp.validator;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

/**
 * Created by rbiedrawa on 2014-12-04.
 */
public class ExchangeRateValidator {
    private static final Logger LOG = Logger.getLogger(ExchangeRateValidator.class);
    public static final DateTime DATE_OF_FIRST_PUBLICATION = new DateTime("2005-01-01");
    public static final DateTimeFormatter DATE_FORMAT = DateTimeFormat.forPattern("yy-MM-dd");

    // hard-coded values of kod_waluty from NBP, ALL to get all currency
    private static final Collection<String> validCurrency = Arrays.asList(
            "USD", "AUD", "CAD", "EUR", "HUF", "CHF", "GBP", "JPY", "CZK",
            "DKK", "NOK", "SEK", "XDR","ALL");

    public static void validateShortName(String shortName){
        if(shortName == null){
            throw new IllegalArgumentException("Currency short name cannot be null");
        }

        if (!validCurrency.contains(shortName.toUpperCase())) {
            String msg = "Exchange rate currency code must be valid.";
            LOG.info(msg + "User typed: " + shortName);

            //FIXME: Narazie nie ma sensu tworzyc Wlasnego wyjatku, zamaly projekt
            throw new IllegalArgumentException(msg);
        }
    }

    public static void validateDates(Date startDate, Date endDate) {

        DateTime sdt = new DateTime(startDate);
        DateTime edt = new DateTime(endDate);

        if (sdt.isAfter(edt)) {
            LOG.error("Start date is after endDate date. Illegal Argument. Throwing Error!!");
            throw new IllegalArgumentException("Start date "
                    + sdt.toString(DATE_FORMAT) + " is after date end date " + edt.toString(DATE_FORMAT));
        }

        if (sdt.isBefore(DATE_OF_FIRST_PUBLICATION)
                || edt.isBefore(DATE_OF_FIRST_PUBLICATION)) {
            LOG.error("Start date or end before 2005-01-01");
            throw new IllegalArgumentException(
                    "Database doesn't contains ExchangeRates before date 2005-01-01. One of your inputs is incorrect, please correct it.");
        }

        if (edt.isAfter(new DateTime())){
            LOG.error("End date cannot be in the future");
            throw new IllegalArgumentException(
                    "End date cannot be in the future");
        }

    }

}
